/**
 * Created by ybf on 2017/6/11.
 */
(function () {
    var top_dom = '<div class="scroll-loading-top"><p class="top-content">下拉刷新</p></div>';
    var bottom_dom = "<div class=\"scroll-loading-bottom\"><p class=\"bottom-content\">正在加载</p></div>";
    var style_css = "<style>.scroll-loading-top, .scroll-loading-bottom {\
    width: 100%;\
    background-color: white;\
    overflow: hidden;\
    height: 0;\
}\
    .scroll-loading-top .top-content, .scroll-loading-bottom .bottom-content {\
    padding: 10px 0;\
    width: 100%;\
    text-align: center;\
    color: #999;\
    background-color: white;\
    font-size: 14px;\
    clear: both;\
}\
.scroll-loading-bottom .bottom-content {\
    border-top: 5px solid #e7e7e7;\
}</style>";
    document.querySelector("head").appendChild(string_to_dom(style_css));
    var sel_dom = document.querySelector(".body-box");
    var ff = string_to_dom(top_dom);
    sel_dom.insertBefore(string_to_dom(top_dom),sel_dom.childNodes[0]);
    sel_dom.appendChild(string_to_dom(bottom_dom));

    var t_start = 0;
    var ts_start_top = 0;
    var t_move = 0;
    var t_move_active = 0;
    var distance_top = 0;

//touchStart
    sel_dom.addEventListener("touchstart",function (e) {
        t_start = e.targetTouches[0].pageY;
        ts_start_top = sel_dom.scrollTop;
    });

//touchMove
    sel_dom.addEventListener("touchmove",function (e) {
        t_move_active = e.targetTouches[0].pageY;
        //滑动的距离
        t_move = -(t_start - t_move_active);
        //距离顶部距离
        distance_top = t_move - ts_start_top;
        /*console.log('top:'+ts_start_top);
         console.log('distance_top:'+distance_top);
         console.log('t_move:'+t_move);*/
        if (distance_top >= 0 && t_move >= 0){
            e.preventDefault();
            document.querySelector('.scroll-loading-top').style.height = t_move*0.4 + 'px';
        }
    });

//touchEnd
    sel_dom.addEventListener('touchend',function (e) {
        if(distance_top >= 40){
            document.querySelector('.scroll-loading-top').style.height = '40px';
        }
    });

//字符串转dom
    function string_to_dom(srt) {
        var temp_dom = document.createElement('div');
        temp_dom.innerHTML = srt;
        return temp_dom.firstChild;
    }

//上拉加载
    var out_box_height = sel_dom.offsetHeight;
    var in_box_height = 0;
    var long_bottom = 0;

    for(var i=0;i<sel_dom.children.length;i++){
        in_box_height += sel_dom.children[i].offsetHeight;
    }
    sel_dom.addEventListener("scroll",function (e) {
        long_bottom = in_box_height - out_box_height - sel_dom.scrollTop;
        console.log(long_bottom);
        if(long_bottom < 1){
            document.querySelector('.scroll-loading-bottom').style.height = '40px';
        }
    });
})();

